from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QColor, QPixmap, QResizeEvent
from qfluentwidgets.components.dialog_box.mask_dialog_base import MaskDialogBase

from resource import WordPng
from tools import WordReplace
from PySide6.QtWidgets import QAbstractItemView, QApplication, QHBoxLayout, QVBoxLayout, QWidget
from qfluentwidgets import (LineEdit, LineEditButton, FluentIcon, PushButton, StateToolTip, InfoBar, ComboBox,
                            TransparentToolButton, TitleLabel, ScrollArea, SubtitleLabel, ImageLabel, BodyLabel,
                            isDarkTheme)
from components import OpenFileDialog, TableFrame
from pandas import read_excel
from common import WordReplaceThread
from ..base import ReturnView


class HelpView(ScrollArea):
    closed = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.widget = QWidget()
        self.setStyleSheet('background-color: transparent;border: none;')
        self.closeButton = TransparentToolButton(FluentIcon.CLOSE, self)
        self.titleLabel = TitleLabel('Word数据替换帮助', self)

        self.subtitleLabel1 = SubtitleLabel('1.准备好需要的数据', self.widget)
        self.imageLabel = ImageLabel(self.widget)
        self.imageLabel.setPixmap(QPixmap(WordPng.PNG1.path()))

        self.subtitleLabel2 = SubtitleLabel('2.准备模板文件', self.widget)
        self.bodyLabel = BodyLabel('模板文件可随意输入，需要替换的数据使用`${key}`来表示。', self.widget)
        self.imageLabel1 = ImageLabel(self.widget)
        self.imageLabel1.setPixmap(QPixmap(WordPng.PNG2.path()))

        self.subtitleLabel3 = SubtitleLabel('3.操作步骤', self.widget)
        self.bodyLabel1 = BodyLabel(
            '''
    1. 选择模板文件后可以自动识别
    2. 选择数据文件，目前只支持Excel
    3. 选择转换后的保存路径
    4. 选择键和值
            ''', self.widget
        )
        self.imageLabel2 = ImageLabel(self.widget)
        self.imageLabel2.setPixmap(QPixmap(WordPng.PNG3.path()))
        self.imageLabel3 = ImageLabel(self.widget)
        self.imageLabel3.setPixmap(QPixmap(QPixmap(WordPng.PNG4.path())))

        self.__initWidget()

    def __initWidget(self):
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setViewportMargins(10, 50, 10, 10)
        self.setWidget(self.widget)
        self.setWidgetResizable(True)

        self.closeButton.setFixedSize(40, 40)

        self.__initLayout()
        self.__initEvent()

    def __initLayout(self):
        self.vBox = QVBoxLayout(self.widget)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(10)
        self.vBox.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.vBox.addWidget(self.subtitleLabel1)
        self.vBox.addWidget(self.imageLabel)
        self.vBox.addWidget(self.subtitleLabel2)
        self.vBox.addWidget(self.bodyLabel)
        self.vBox.addWidget(self.imageLabel1)
        self.vBox.addWidget(self.subtitleLabel3)
        self.vBox.addWidget(self.bodyLabel1)
        self.vBox.addWidget(self.imageLabel2)
        self.vBox.addWidget(self.imageLabel3)

    def __initEvent(self):
        self.closeButton.clicked.connect(self.on_closeButton_clicked)

    def resizeEvent(self, event: QResizeEvent):
        self.titleLabel.move(10, 10)
        self.closeButton.move(self.width() - 45, 10)
        super().resizeEvent(event)

    def on_closeButton_clicked(self):
        self.closed.emit()


class HelpDialog(MaskDialogBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        c = 0 if isDarkTheme() else 255
        self.setMaskColor(QColor(c, c, c, 200))

        self.vBox = QVBoxLayout(self.widget)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(0)
        self.vBox.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.helpView = HelpView()
        self.helpView.closed.connect(self.close)
        self.vBox.addWidget(self.helpView)


class WordReplaceFrame(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.helpButton = TransparentToolButton(FluentIcon.HELP, self)
        self.helpButton.setFixedSize(40, 40)

        self.title = TitleLabel('Word数据替换', self)

        self.templatePath = LineEdit()
        self.templatePath.setFixedHeight(30)
        self.templatePath.setPlaceholderText('请选择模板文件。。。')
        self.templatePath.setClearButtonEnabled(True)
        self.openFileButton = LineEditButton(FluentIcon.FOLDER, self.templatePath)
        self.templatePath.hBoxLayout.addWidget(self.openFileButton)

        self.startButton = PushButton()
        self.startButton.setText('开始')

        self.excelEdit = LineEdit()
        self.excelEdit.setFixedHeight(30)
        self.excelEdit.setPlaceholderText('请选择Excel数据文件。。。')
        self.excelEdit.setClearButtonEnabled(True)
        self.openExcelButton = LineEditButton(FluentIcon.FOLDER, self.templatePath)
        self.excelEdit.hBoxLayout.addWidget(self.openExcelButton)

        self.saveEdit = LineEdit()
        self.saveEdit.setFixedHeight(30)
        self.saveEdit.setPlaceholderText('请选择Word文件保存路径。。。')
        self.saveEdit.setClearButtonEnabled(True)
        self.saveDirButton = LineEditButton(FluentIcon.FOLDER, self.templatePath)
        self.saveEdit.hBoxLayout.addWidget(self.saveDirButton)

        self.table = TableFrame()
        self.table.setHeaders(['键', '值'])
        self.table.tableView.setEditTriggers(QAbstractItemView.EditTrigger.CurrentChanged)

        self.stateToolTip = StateToolTip('转换中...', '正在根据模板创建Word文件，请稍后...', parent=self)
        self.stateToolTip.hide()

        self.replace_thread = WordReplaceThread(self)

        self.initEvent()
        self.initLayout()

    def initEvent(self):
        self.helpButton.clicked.connect(self.on_helpButton_event)
        self.returnButton.clicked.connect(self.returned_event)
        self.openFileButton.clicked.connect(self.get_template_path)
        self.startButton.clicked.connect(self.startButtonEvent)
        self.openExcelButton.clicked.connect(self.get_excel_path)
        self.saveDirButton.clicked.connect(self.get_save_dir)

        self.replace_thread.started.connect(self.started_thread)
        self.replace_thread.error.connect(lambda msg: InfoBar.error('错误', msg, duration=5000, parent=self))
        self.replace_thread.finished.connect(self.finished_thread)

    def initLayout(self):
        self.hBox.addWidget(self.helpButton, 0, Qt.AlignmentFlag.AlignRight)
        self.vBox.addWidget(self.title, 0, Qt.AlignmentFlag.AlignHCenter)
        self.vBox.addWidget(self.templatePath)
        self.vBox.addWidget(self.excelEdit)
        self.vBox.addWidget(self.saveEdit)
        self.vBox.addWidget(self.table)
        self.vBox.addWidget(self.startButton)

    def get_template_path(self):
        file = OpenFileDialog(self).getOpenFileName(filter='Word文件(*.docx;*.doc)')[0]
        self.templatePath.setText(file)
        if file == '':
            return
        self.table.clear()
        word = WordReplace(file)
        self.table.addItems(word.get_dict().items())
        self.table.addItem(['保存文件名称', ''])

    def get_save_dir(self):
        file = OpenFileDialog(self).getExistingDirectory()
        self.saveEdit.setText(file)

    def startButtonEvent(self):
        templatePath = self.templatePath.text()
        excelPath = self.excelEdit.text()
        savePath = self.saveEdit.text()
        if templatePath == '' or savePath == '' or excelPath == '':
            InfoBar.warning('提示', '请选择相关路径', duration=3000, parent=self)
            return
        if len(self.table.getColumnValues(0)) == 0:
            return
        data = dict(zip(self.table.getColumnValues(0), self.table.getColumnWidgetText(1)))
        self.replace_thread.set_value(templatePath, excelPath, savePath, data)
        self.replace_thread.start()

    def get_excel_path(self):
        file = OpenFileDialog(self).getOpenFileName(filter='Excel表格文件(*.xlsx;*.xls)')[0]
        self.excelEdit.setText(file)
        if file == '':
            return
        columns = read_excel(file).columns

        for index, col in enumerate(self.table.getColumnValues(0)):
            comboBox = ComboBox()
            comboBox.addItems(columns)
            comboBox.currentText()
            self.table.setCellWidget(index, 1, comboBox)

    def started_thread(self):
        self.stateToolTip.show()

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('成功', 'Word文件转换成功', parent=self)

    def returned_event(self):
        self.returned.emit()

    def on_helpButton_event(self):
        self.helpDialog = HelpDialog(self)
        self.helpDialog.show()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    win = WordReplaceFrame()
    win.resize(600, 600)
    win.show()
    sys.exit(app.exec())
